<template>
  <div class="app-container edit-post-layout">
    <!-- 顶部按钮区域 - 固定 -->
    <div v-loading="pageLoading" class="top-toolbar">
      <div class="toolbar-left">
        <el-dropdown trigger="click" class="nav-dropdown">
          <i class="el-icon-menu nav-dropdown-icon" title="导航菜单" />
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="goBack">
              <i class="el-icon-back" /> 返回
            </el-dropdown-item>
            <el-dropdown-item @click.native="goHome">
              <i class="el-icon-house" /> 首页
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <span class="config-toggle" @click="changeShow">
          编辑系统内容
          <el-icon v-if="show_configs" title="点击折叠配置选项" class="el-icon-arrow-up" />
          <el-icon v-else title="点击打开配置选项" class="el-icon-arrow-down" />
        </span>
      </div>

      <div class="toolbar-center">
        <el-tag>PL：{{ owner__username }}</el-tag>
        <el-tag>写手：{{ writer_username }}</el-tag>
      </div>

      <div class="toolbar-right">
        <!-- 分享相关 -->
        <el-link v-if="share_token !== ''" :href="'https://s.lianf.com/?s='+share_token" target="_blank" class="toolbar-item">
          {{ share_token }}
        </el-link>
        <el-button v-else type="success" size="mini" class="toolbar-item" @click="handleAddPostShare">
          添加分享
        </el-button>

        <!-- 状态开关 -->
        <el-switch
          v-model="writer_finished"
          class="toolbar-item"
          title="标记写作完成"
          active-color="#13ce66"
          inactive-color="#ff4949"
          @change="changeWriterFinished"
        />

        <el-switch
          v-if="is_manager"
          v-model="owner_pass"
          class="toolbar-item"
          title="标记审核通过"
          active-color="#13ce66"
          inactive-color="#ff4949"
          @change="handleChangeOwnerPass"
        />

        <!-- 文章历史 -->
        <span v-if="post_id" class="toolbar-item history-btn" @click="handleViewHistory">
          <svg-icon icon-class="post_history" style="margin-right:5px;" />文章历史
        </span>

        <!-- 保存和发布按钮 -->
        <el-dropdown
          split-button
          type="primary"
          size="mini"
          title="保存 (Ctrl+S)"
          class="toolbar-item"
          :disabled="!saveDisabled"
          @click="handleClickSave('1')"
        >
          {{ post_id ? '更新' : '保存' }}
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native.stop="handleClickSave('2')">保存为版本</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>

        <el-dropdown
          split-button
          type="success"
          size="mini"
          title="发布文章到站点"
          class="toolbar-item"
          @click="handleClickPublish"
        >
          发布
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native.stop="handleThirdPublic">发布到第三方</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>

    <!-- 配置区域 - 可折叠 -->
    <div v-if="show_configs" class="config-area">
      <div class="config-content">
        <el-row :gutter="10">
          <el-col :span="4">
            <el-select
              v-model="category_id"
              v-loading="categoriesLoading"
              placeholder="分类"
              size="mini"
              clearable
              :disabled="!editable"
              style="width: 100%"
            >
              <el-option
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select
              v-model="language_id"
              v-loading="languagesLoading"
              placeholder="语言"
              size="mini"
              clearable
              :disabled="!editable"
              style="width: 100%"
            >
              <el-option
                v-for="language in languages"
                :key="language.id"
                :label="language.name"
                :value="language.id"
              />
            </el-select>
          </el-col>
          <el-col :span="8">
            <el-select
              v-model="selected_webs"
              v-loading="websLoading"
              size="mini"
              placeholder="输出站点"
              :disabled="!editable"
              multiple
              clearable
              filterable
              style="width: 70%"
            >
              <el-option
                v-for="web in webs"
                :key="web.id"
                :label="web.url"
                :value="web.id"
              />
            </el-select>
            <el-button type="warning" size="mini" title="管理站点" icon="el-icon-setting" @click="webVisible = true" />
            <el-button icon="el-icon-refresh" size="mini" title="刷新" type="info" @click="handleFetchWebs" />
          </el-col>
          <el-col :span="8">
            <!-- 功能按钮 -->
            <el-tooltip v-if="this.$store.getters.roles.indexOf('ai_image_user') !== -1" effect="dark" :content="auto_state_tips" placement="top">
              <el-button
                :type="optiomize_processed ? 'success': 'primary'"
                size="mini"
                :loading="insertImageloading"
                @click="handleInsertImage"
              >
                {{ optiomize_processed ? '已优化' : (auto_state_tips ? auto_state_tips : '优化内容') }}
              </el-button>
            </el-tooltip>
            <el-button :type="insertlink_processed ? 'success': 'primary'" size="mini" :loading="insertlinkloading" @click="handleInsertLink">
              {{ insertlink_processed ? '已插入': '插入内链' }}
            </el-button>
            <el-button :type="DuplicateCheck_processed ? 'success': 'primary'" size="mini" :loading="DuplicateCheck_loading" @click="handleDuplicateCheck">
              {{ DuplicateCheck_processed ? '已查' + duplicate_count + '处重复': '查重' }}
            </el-button>
            <el-button type="warning" size="mini" title="管理翻译任务" @click="handleOpenTranslateTask">
              翻译任务
            </el-button>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 主体内容区域 -->
    <div class="main-content" :class="{ 'with-config': show_configs }">
      <!-- 翻译版本对照区域 - 可折叠 -->
      <div
        v-if="showTranslateCompare && translateVersions.length > 0"
        class="translate-compare-area"
        :style="{ width: translateAreaWidth + '%' }"
      >
        <div class="translate-header">
          <div class="translate-header-content">
            <div class="translate-select-section">
              <span class="translate-title">翻译版本</span>
              <el-select
                v-model="selectedTranslateVersion"
                size="mini"
                placeholder="选择翻译版本"
                style="width: 200px;"
                @change="handleTranslateVersionChange"
              >
                <el-option
                  v-for="version in translateVersions"
                  :key="version.id"
                  :label="`${version.language__name} - ${version.title}`"
                  :value="version.id"
                />
              </el-select>
            </div>

            <div class="translate-controls">
              <!-- 同步滚动控制 -->
              <el-tooltip content="启用/禁用同步滚动" placement="top">
                <el-button
                  type="text"
                  size="mini"
                  :icon="syncScrollEnabled ? 'el-icon-link' : 'el-icon-unlock'"
                  :class="{ 'sync-enabled': syncScrollEnabled }"
                  @click="toggleSyncScroll"
                />
              </el-tooltip>

              <el-tooltip :content="`当前模式：${scrollSyncMode === 'ratio' ? '比例同步' : '段落同步'}`" placement="top">
                <el-button
                  v-if="syncScrollEnabled"
                  type="text"
                  size="mini"
                  :icon="scrollSyncMode === 'ratio' ? 'el-icon-s-operation' : 'el-icon-menu'"
                  @click="toggleSyncMode"
                />
              </el-tooltip>

              <el-tooltip content="重新对齐滚动位置" placement="top">
                <el-button
                  v-if="syncScrollEnabled"
                  type="text"
                  size="mini"
                  icon="el-icon-refresh"
                  @click="realignScrollPosition"
                />
              </el-tooltip>

              <el-tooltip content="刷新翻译内容" placement="top">
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-refresh-right"
                  @click="fetchTranslateVersionContent"
                />
              </el-tooltip>

              <el-tooltip content="关闭翻译对照" placement="top">
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-close"
                  @click="showTranslateCompare = false"
                />
              </el-tooltip>
            </div>
          </div>
        </div>

        <div v-if="getSelectedTranslateContent()" class="translate-content-area">
          <div class="translate-content-display" v-html="getSelectedTranslateContent().content" />
        </div>
      </div>

      <!-- 可拖拽的分割条 -->
      <div
        v-if="showTranslateCompare && translateVersions.length > 0"
        class="resize-handle"
        @mousedown="handleResizeStart"
      >
        <div class="resize-line" />
      </div>

      <!-- 左侧编辑区域 - 可滚动 -->
      <div
        class="edit-area"
        :class="{ 'with-translate': showTranslateCompare && translateVersions.length > 0 }"
        :style="showTranslateCompare && translateVersions.length > 0 ? { width: editAreaWidth + '%' } : {}"
      >
        <div class="title-section">
          <div class="title-input-wrapper">
            <el-input
              v-model="title"
              placeholder="请输入文章标题"
              :disabled="!editable"
              size="small"
              clearable
            />
            <el-tooltip
              v-if="translateVersions.length > 0"
              :content="showTranslateCompare ? '隐藏翻译对照' : '显示翻译对照'"
              placement="top"
            >
              <el-button
                type="text"
                size="mini"
                :icon="showTranslateCompare ? 'el-icon-d-arrow-right' : 'el-icon-d-arrow-left'"
                @click="showTranslateCompare = !showTranslateCompare"
              />
            </el-tooltip>
          </div>
        </div>

        <div class="editor-section">
          <a-i-tiptap
            ref="mt"
            v-model.lazy="content"
            :height="600"
            :show-toolbar="true"
            :show-ai-toolbar="false"
            ai-app="content"
            @save="handleEditorSave"
            @selection-cleared="handleClearSelection"
          />
        </div>

        <div class="status-section">
          <el-tooltip v-if="last_post_data.account_id !== undefined && last_post_data.post_id !== post_id" class="item" effect="dark" :content="'account:' + last_post_data.domain + '目录:'+ last_post_data.categories.map( item=> { return item.name})" placement="top">
            <el-button v-if="last_post_data.account_id !== undefined && last_post_data.post_id !== post_id" type="danger" size="mini" :loading="publishloading" @click="handlePublichPost">继续发布</el-button>
          </el-tooltip>
          <el-button v-if="publishloading" type="danger" size="mini" :loading="publishloading">发布中...</el-button>
          <el-link v-if="post_link !== ''" target="_blank" :href="post_link">打开【发布成功】</el-link>
        </div>
      </div>

      <!-- 可拖拽的分隔条(编辑区与侧边栏之间) -->
      <div
        class="main-resize-handle"
        @mousedown="handleMainResizeStart"
      >
        <div class="resize-line" />
      </div>

      <!-- 右侧功能区域 - 可调整宽度 -->
      <div class="sidebar-area" :style="{ width: sidebarWidth + 'px' }">
        <!-- Tab切换区域 -->
        <div v-if="post_id" class="sidebar-tabs-card">
          <el-card class="box-card">
            <el-tabs v-model="sidebarActiveTab" type="border-card">
              <!-- 1. AI写作助手 Tab -->
              <el-tab-pane name="ai">
                <span slot="label">
                  <i class="el-icon-chat-dot-round" style="color: #1EB7E6;" /> AI助手
                </span>
                <div class="tab-content-wrapper">
                  <AIinnerChat
                    ref="aiChat"
                    api-url="/static_web/api/ai/chat/"
                    handler-name="post_writing_assistant"
                    engine="google/gemini-3-pro-preview"
                    :context-data="aiChatContext"
                    :welcome-message="aiWelcomeMessage"
                    :quick-commands="postQuickCommands"
                    placeholder="请告诉我你想做什么..."
                    @content-update="handleAIContentUpdate"
                    @clear-selection="handleClearSelection"
                  />
                </div>
              </el-tab-pane>

              <!-- 2. SEO检查 Tab -->
              <el-tab-pane name="seo">
                <span slot="label">
                  <el-badge :value="basic_seo_warnings.length" :hidden="!basic_seo_warnings.length" type="warning">
                    <span><i class="el-icon-warning" /> SEO检查</span>
                  </el-badge>
                </span>
                <div class="tab-content-wrapper">
                  <div v-if="basic_seo_warnings && basic_seo_warnings.length > 0">
                    <el-alert
                      v-for="(warning, index) in basic_seo_warnings"
                      :key="index"
                      :title="warning"
                      type="warning"
                      :closable="false"
                      show-icon
                      style="margin-bottom: 8px;"
                    />
                  </div>
                  <el-empty v-else description="暂无SEO问题" :image-size="80" />
                </div>
              </el-tab-pane>

              <!-- 3. 内链列表 Tab -->
              <el-tab-pane name="internalLinks">
                <span slot="label">
                  <i class="el-icon-link" /> 内链列表
                </span>
                <div class="tab-content-wrapper">
                  <cms-inner-link :domain="root_domain" />
                </div>
              </el-tab-pane>

              <!-- 4. 发布记录 Tab -->
              <el-tab-pane name="publish">
                <span slot="label">
                  <i class="el-icon-document" /> 发布记录
                </span>
                <div class="tab-content-wrapper">
                  <postpublishrecord :post_id="post_id" />
                </div>
              </el-tab-pane>
            </el-tabs>
          </el-card>
        </div>
      </div>
    </div>

    <web :web-visible="webVisible" @reload="handleFetchWebs" @closeWebDialog="webVisible=false" />
    <post-history
      :history-visible="historyVisible"
      :post_id="post_id"
      @applyHistory="applyHistory"
      @closeHistoryDialog="historyVisible=false"
    />
    <wppromote
      :promote-visiable="promoteVisiable"
      :project_id="project_id"
      :post_id="post_id"
      :tags="post_tags"
      :imagesurls="imagesurls"
      :web="selected_webs ? selected_webs[0]: ''"
      @closewppromoteDialog="promoteVisiable=false"
    />
    <translate-task-manager
      :visible.sync="translateTaskVisible"
      :post-id="post_id"
      :post-title="title"
      @refresh-post="handleTranslateTaskRefresh"
    />
  </div>
</template>

<script>
import { Get as GetProjects } from '@/api/erp/elicink/project'
import { Get as GetTitleTemplate } from '@/api/cms/titleTemplate'
import { Get as GetCategories } from '@/api/cms/category'
import { Get as GetLanguages } from '@/api/cms/language'
import { Get as GetPosts, Post as AddPost, Put as PutPost, duplicate_check, InsertInnerLink, InsertInnerImage, AddPostShare } from '@/api/cms/post'
import { Get as GetWebs } from '@/api/cms/web'
import AITiptap from '@/components/AITiptap'
import AIinnerChat from '@/components/AIInnerChat'
import web from '@/views/cms/elements/web'
import postHistory from '@/views/cms/elements/postHistory'
import wppromote from '@/views/cms/elements/wppromote'
import { Post as SendPostRecord } from '@/api/cms/postpublish'
import postpublishrecord from '@/views/cms/elements/postpublishrecord'
import CmsInnerLink from '@/views/cms/elements/cmsinnerlink'
import Cookies from 'js-cookie'

import { has_permission } from '../../assets/common'
import Topicmaterial from './elements/topicmaterial'
import TranslateTaskManager from '@/components/TranslateTaskManager'

export function getToken(key) {
  const v = Cookies.get(key)
  return v && parseInt(v) || null
}

export function setToken(key, value) {
  return Cookies.set(key, value, { expires: 30 })
}

// const ProjectKey = 'cms_project_id'
const CategoryKey = 'cms_category_id'
const LanguageKey = 'cms_language_id'

export default {
  components: { Topicmaterial, postHistory, AITiptap, AIinnerChat, web, wppromote, postpublishrecord, CmsInnerLink, TranslateTaskManager },

  // 路由离开守卫
  beforeRouteLeave(to, from, next) {
    this.checkBeforeLeave(next)
  },
  data() {
    return {
      post_tags: [],
      optiomize_processed: false,
      insertlink_processed: false,
      insertlinkloading: false,
      insertImageloading: false,
      DuplicateCheck_processed: false,
      duplicate_count: 0,
      DuplicateCheck_loading: false,
      last_post_data: {},
      publishloading: false,
      post_link: '',
      share_token: '',
      show_configs: true,
      myroles: [],
      post_id: null,
      writer_finished: false,
      is_manager: false,
      owner_pass: false,
      owner__username: '',
      writer_username: '',
      pageLoading: false,

      editable: true, // 是否有权限进行编辑
      projects: [],
      project_id: this.$store.getters.projectId,
      projectsLoading: false,
      topic_description: '',
      topic_id: '',
      materialVisible: true,
      root_domain: '',
      categories: [],
      category_id: null,
      categoriesLoading: false,

      languages: [],
      language_id: null,
      languagesLoading: false,

      posts: [],
      source_id: null,
      postsLoading: false,

      webs: [],
      selected_webs: [],
      websLoading: false,

      title: '',
      content: '',

      // 右侧Tab切换
      sidebarActiveTab: 'ai', // 默认显示AI助手tab
      saveDisabled: false,

      // AI助手欢迎消息
      aiWelcomeMessage: `你好！我是AI文章编辑助手 ✨

我可以帮你：
1. **分析当前内容** - 文章中意思重复，关键词堆砌的段落给我列出来。
2. **SEO 优化** - 请分析我文章中关键词布局是否合理
3. **内容创作** - 写开头、写总结、扩展内容
4. **结构调整** - 添加小标题、调整段落结构
5. **改写选中内容** - 请在左侧编辑区选中内容，然后提出修改需求。

💡 **使用方法：**
- 直接告诉我你想做什么，例如："帮我写一个引人入胜的开头"
- 选中文章中的部分文字后提问，我会针对选中内容进行优化
- 如果没有选中文字，我会基于整篇文章内容来回答
- 请给出具体要求，要求越具体越好

现在，请告诉我你想做什么？`,

      // 保存编辑器选区信息(解决焦点转移导致选区丢失问题)
      savedSelection: {
        from: 0,
        to: 0,
        text: ''
      },
      // 保存选中的 mark ID (用于视觉高亮)
      selectionMarkId: null,
      init_text: '',
      imagesurls: [],
      titleTemplates: [],
      titleLoading: false,

      subjectVisible: false,
      webVisible: false,

      historyVisible: false,
      promoteVisiable: false,
      translateTaskVisible: false, // 翻译任务抽屉显示状态
      last_content: '',
      auto_state_tips: '', // 自动优化状态提示
      autoStateTimer: null, // 轮询定时器
      autoStatePollingInterval: 2000, // 轮询间隔(毫秒)
      basic_seo_warnings: [], // SEO检查提醒列表

      // 翻译版本相关
      translateVersions: [], // 翻译版本列表
      selectedTranslateVersion: null, // 当前选择的翻译版本
      showTranslateCompare: false, // 是否显示翻译对照

      // 拖拽调整宽度相关
      translateAreaWidth: 42, // 翻译对照区域宽度百分比（默认比编辑器窄80px左右）
      editAreaWidth: 53, // 编辑区域宽度百分比
      isDragging: false, // 是否正在拖拽
      startX: 0, // 拖拽开始时的鼠标X坐标
      startTranslateWidth: 42, // 拖拽开始时的翻译区域宽度

      // 主区域拖拽调整宽度相关
      sidebarWidth: 500, // 右侧边栏宽度（像素）
      isMainDragging: false, // 是否正在拖拽主分隔条
      mainStartX: 0, // 拖拽开始时的鼠标X坐标
      mainStartSidebarWidth: 500, // 拖拽开始时的侧边栏宽度

      // 同步滚动相关
      syncScrollEnabled: true, // 是否启用同步滚动
      isScrollSyncing: false, // 是否正在同步滚动（防止循环）
      scrollSyncMode: 'ratio', // 同步模式：'ratio'(比例) 或 'paragraph'(段落)
      editAreaScrollListener: null, // 编辑区域滚动监听器
      translateAreaScrollListener: null, // 翻译区域滚动监听器
      editParagraphMap: [], // 编辑区域段落映射表
      translateParagraphMap: [], // 翻译区域段落映射表
      scrollDebounceTimer: null // 滚动防抖定时器
    }
  },
  watch: {
    content(v) {
      this.saveDisabled = v !== this.init_text && this.title
    },
    title(v) {
      this.saveDisabled = v !== this.init_text && this.title
    },
    // 监听翻译对照显示状态变化
    showTranslateCompare(newVal) {
      if (newVal) {
        // 显示翻译对照时，延迟初始化同步滚动
        this.$nextTick(() => {
          this.initSyncScroll()
        })
      } else {
        // 隐藏翻译对照时，清理滚动监听器
        this.removeScrollListeners()
      }
    }
  },
  computed: {
    // AI对话上下文数据
    aiChatContext() {
      // 优先使用保存的选区文本(解决焦点转移导致选区丢失问题)
      let selectedText = this.savedSelection.text || ''
      let currentContent = this.content // 默认使用组件数据作为备选

      if (this.$refs.mt && this.$refs.mt.editor) {
        const editor = this.$refs.mt.editor

        // 如果没有保存的选区,再尝试从编辑器获取
        if (!selectedText) {
          const { from, to } = editor.state.selection
          selectedText = editor.state.doc.textBetween(from, to, '\n')
        }

        // 获取编辑器当前的HTML内容（包含用户的实时修改）
        currentContent = editor.getHTML()
      }

      return {
        post_id: this.post_id,
        title: this.title,
        content: currentContent, // 使用编辑器的实时内容
        selected_text: selectedText,
        category_id: this.category_id,
        language_id: this.language_id
      }
    },
    // AI助手快捷命令（动态包含域名）
    postQuickCommands() {
      const domain = this.root_domain || ''
      return [
        {
          label: '生成信息图',
          text: `请根据文章内容生成一张信息图${domain ? `，品牌域名是 ${domain}` : ''}`,
          icon: 'el-icon-picture-outline',
          type: 'success',
          fillOnly: true
        },
        {
          label: '生成文章插图',
          text: `请根据文章内容生成段落插图5张${domain ? `，品牌域名是 ${domain}` : ''}`,
          icon: 'el-icon-picture',
          type: 'primary',
          fillOnly: true
        }
      ]
    }
  },
  created() {
    console.log(has_permission('out_writer'))
    // 隐藏系统导航栏实现全屏编辑
    this.$store.dispatch('setHideNavbar', true)

    // 恢复用户的宽度偏好
    this.restoreWidthPreference()

    // this.handleFetchProjects()
    this.handleFetchCategories()
    this.handleFetchLanguages()
    // this.handleFetchPosts()
    this.handleFetchWebs()
    // this.handleFetchTitleTemplates()

    this.post_id = this.$route.params.post_id || null

    if (this.post_id) {
      this.pageLoading = true
      GetPosts(this.post_id)
        .then(response => {
          this.pageLoading = false
          this.editable = response.data.editable
          this.project_id = response.data.project_id
          this.topic_id = response.data.topic_id
          this.topic_description = response.data.topic_description
          this.category_id = response.data.category_id
          this.language_id = response.data.language_id
          this.source_id = response.data.source_id
          this.post_tags = [response.data.keyword]
          this.writer_finished = response.data.writer_finished
          this.selected_webs = response.data.webs.map(m => m.id)
          // 提取第一个web的url作为域名
          if (this.selected_webs.length > 0) {
            this.root_domain = response.data.webs[0].url
            // 从url中提取根域名
            this.root_domain = this.root_domain.replace(/(http|https):\/\//, '').split('/')[0]
          }
          this.title = response.data.title
          this.owner_pass = response.data.owner_pass
          this.is_manager = response.data.is_manager
          this.owner__username = response.data.owner__username
          this.writer_username = response.data.writer_username
          this.last_content = response.data.content
          this.imagesurls = this.getImageUrls(response.data.content)
          this.basic_seo_warnings = response.data.basic_seo_warnings || []

          // 处理翻译版本数据
          this.translateVersions = response.data.children || []
          if (this.translateVersions.length > 0) {
            // 默认选择第一个翻译版本
            this.selectedTranslateVersion = this.translateVersions[0].id
            this.showTranslateCompare = true
          }

          console.log(response.data)
          this.$nextTick(() => {
            this.$refs.mt.setContent(response.data.content)
          })
        })
    } else {
      this.pageLoading = false
      this.project_id = this.$store.getters.projectId
      this.category_id = getToken(CategoryKey)
      this.language_id = getToken(LanguageKey)
    }
  },
  mounted() {
    // 添加键盘事件监听器
    document.addEventListener('keydown', this.handleKeyDown)
    // 添加页面刷新/关闭监听器
    window.addEventListener('beforeunload', this.handleBeforeUnload)

    // 恢复用户侧边栏宽度偏好
    this.restoreSidebarWidth()

    // 初始化同步滚动
    this.$nextTick(() => {
      this.initSyncScroll()

      // 监听编辑器选区变化,实时保存选区信息(解决焦点转移导致选区丢失问题)
      this.setupSelectionTracking()
    })
  },
  beforeDestroy() {
    this.stopAutoStatePolling()
    // 移除键盘事件监听器
    document.removeEventListener('keydown', this.handleKeyDown)
    // 移除页面刷新/关闭监听器
    window.removeEventListener('beforeunload', this.handleBeforeUnload)
    // 清理同步滚动监听器
    this.removeScrollListeners()
    // 恢复系统导航栏
    this.$store.dispatch('setHideNavbar', false)
  },
  methods: {
    // 设置编辑器选区跟踪(解决焦点转移导致选区丢失问题)
    setupSelectionTracking() {
      if (!this.$refs.mt || !this.$refs.mt.editor) {
        console.warn('编辑器未就绪,无法设置选区跟踪')
        return
      }

      const editor = this.$refs.mt.editor

      // 监听编辑器的 selectionUpdate 事件
      editor.on('selectionUpdate', ({ editor }) => {
        const { from, to } = editor.state.selection
        const text = editor.state.doc.textBetween(from, to, '\n')

        // 只有当有实际选中内容时才保存(避免保存空选区)
        if (from !== to && text.trim()) {
          this.savedSelection = {
            from,
            to,
            text
          }
          console.log('保存选区:', { from, to, textLength: text.length })
        }
      })

      // 监听 blur 事件,在失去焦点时添加视觉标记
      editor.on('blur', ({ editor }) => {
        const { from, to } = editor.state.selection
        const text = editor.state.doc.textBetween(from, to, '\n')

        if (from !== to && text.trim()) {
          // 保存选区数据
          this.savedSelection = {
            from,
            to,
            text
          }
          console.log('编辑器失焦,保存选区:', { from, to, textLength: text.length })

          // 添加临时高亮标记(使用 mark)
          try {
            editor.chain()
              .setTextSelection({ from, to })
              .setMark('highlight', { color: '#b3d4fc' })
              .run()
            console.log('✓ 已添加选区视觉标记')
          } catch (e) {
            console.warn('添加选区标记失败:', e)
          }
        }
      })

      // 监听 focus 事件,重新获得焦点时移除视觉标记
      editor.on('focus', ({ editor }) => {
        // 如果有保存的选区,恢复选中状态并移除标记
        if (this.savedSelection.from !== 0 && this.savedSelection.to !== 0) {
          try {
            editor.chain()
              .setTextSelection({
                from: this.savedSelection.from,
                to: this.savedSelection.to
              })
              .unsetMark('highlight')
              .run()
            console.log('✓ 已恢复选区并移除标记')
          } catch (e) {
            console.warn('恢复选区失败:', e)
          }
        }
      })

      console.log('✓ 编辑器选区跟踪已启用')
    },

    // 处理清除选区
    handleClearSelection() {
      // 清空保存的选区数据
      this.savedSelection = {
        from: 0,
        to: 0,
        text: ''
      }

      // 如果编辑器存在,移除高亮标记
      if (this.$refs.mt && this.$refs.mt.editor) {
        const editor = this.$refs.mt.editor
        try {
          // 移除所有 highlight mark
          editor.chain()
            .focus()
            .unsetMark('highlight')
            .run()
          console.log('✓ 已清除选区标记')
        } catch (e) {
          console.warn('清除选区标记失败:', e)
        }
      }
    },

    // 处理AI内容更新
    handleAIContentUpdate(data) {
      console.log('收到AI内容更新:', data)

      if (!this.$refs.mt || !this.$refs.mt.editor) {
        this.$message.error('编辑器未就绪')
        return
      }

      const editor = this.$refs.mt.editor

      // 优先使用保存的选区,如果没有则使用当前选区
      let from = this.savedSelection.from
      let to = this.savedSelection.to

      if (from === 0 && to === 0) {
        // 没有保存的选区,使用当前选区
        const selection = editor.state.selection
        from = selection.from
        to = selection.to
      }

      try {
        if (data.type === 'replace' && from !== to) {
          // 替换选中的文本(使用保存的选区位置)
          editor.chain()
            .focus()
            .setTextSelection({ from, to })
            .unsetMark('highlight') // 移除高亮标记
            .deleteRange({ from, to })
            .insertContentAt(from, data.content)
            .run()

          // 清空保存的选区
          this.savedSelection = { from: 0, to: 0, text: '' }

          this.$message.success('已更新选中内容')
        } else if (data.type === 'insert') {
          // 在当前位置插入内容
          editor.chain()
            .focus()
            .insertContent(data.content)
            .run()

          this.$message.success('已插入内容')
        } else if (data.type === 'full_replace') {
          // 替换整个文档内容
          editor.commands.setContent(data.content)
          this.$message.success('已更新全部内容')
        } else {
          this.$message.warning('未知的更新类型: ' + data.type)
        }

        // 更新组件的content数据
        this.$nextTick(() => {
          this.content = editor.getHTML()
        })
      } catch (error) {
        console.error('更新内容失败:', error)
        this.$message.error('更新内容失败: ' + error.message)
      }
    },

    // 处理键盘快捷键
    handleKeyDown(event) {
      // Ctrl+S 保存
      if (event.ctrlKey && event.key === 's') {
        event.preventDefault() // 阻止浏览器默认的保存行为

        try {
          // 先从编辑器获取最新内容
          if (this.$refs.mt) {
            const currentContent = this.$refs.mt.getContent()
            if (currentContent) {
              this.content = currentContent
            }
          }

          // 检查内容和标题
          if (!this.content && !this.title) {
            this.$message.warning('请先输入标题或内容')
            return
          }

          console.log('Ctrl+S 保存 - 内容长度:', this.content?.length || 0)
          this.handleClickSave('1')
        } catch (error) {
          console.error('保存时发生错误:', error)
          this.$message.error('保存失败，请重试')
        }
      }
    },
    getImageUrls(content) {
      if (!content) return []
      const imgRegex = /<img[^>]+src="([^">]+)"/g
      const urls = []
      let match

      while ((match = imgRegex.exec(content)) !== null) {
        const url = match[1]
        // 过滤掉base64图片
        if (!url.startsWith('data:')) {
          urls.push(url)
        }
      }

      return urls
    },
    handleAddPostShare() {
      AddPostShare(this.post_id, null).then(response => {
        this.share_token = response.share_token
        this.$message.success('插入成功')
      })
        .catch(e => {
          this.$message.error('获取失败')
        })
    },
    // 开始轮询状态
    startAutoStatePolling() {
      // 先清除可能存在的定时器
      if (this.autoStateTimer) {
        clearInterval(this.autoStateTimer)
      }

      // 立即执行一次
      this.getAutoStateTips()

      // 设置定时器定期查询状态
      this.autoStateTimer = setInterval(() => {
        this.getAutoStateTips()
      }, this.autoStatePollingInterval)
    },

    // 停止轮询
    stopAutoStatePolling() {
      if (this.autoStateTimer) {
        clearInterval(this.autoStateTimer)
        this.autoStateTimer = null
      }
    },

    // 获取优化状态
    getAutoStateTips() {
      GetPosts(this.post_id)
        .then(response => {
          console.log('获取状态成功:', response.data.auto_state_tips)
          this.auto_state_tips = response.data.auto_state_tips || ''
          // 如果状态为finished，停止轮询并刷新内容
          if (this.auto_state_tips === 'finished' || this.auto_state_tips === 'error') {
            this.stopAutoStatePolling()
            this.refreshContent()
            this.optiomize_processed = true
            this.insertImageloading = false
            this.$message.success('内容优化完成')
          }
        })
        .catch(e => {
          console.error('获取状态失败:', e)
          this.insertImageloading = false
        })
    },

    // 刷新内容
    refreshContent() {
      GetPosts(this.post_id)
        .then(response => {
          this.last_content = response.data.content
          this.basic_seo_warnings = response.data.basic_seo_warnings || []
          this.$refs.mt.setContent(response.data.content)
        })
        .catch(e => {
          console.error('刷新内容失败:', e)
        })
    },

    handleInsertImage() {
      this.insertImageloading = true
      InsertInnerImage({ post_id: this.post_id }).then(response => {
        this.$message.success('开始优化内容')
        this.startAutoStatePolling() // 开始轮询状态
      })
        .catch(e => {
          this.insertImageloading = false
          this.startAutoStatePolling() // 开始轮询状态
        })
    },
    handleDuplicateCheck() {
      // this.handleClickSave('1')
      this.DuplicateCheck_loading = true
      duplicate_check({ post_id: this.post_id }).then(response => {
        this.last_content = response.html
        this.$refs.mt.setContent(response.html)
        this.$message.success('处理成功,总共有' + response.count + '处重复')
        this.DuplicateCheck_processed = true
        this.DuplicateCheck_loading = false
        this.duplicate_count = response.count
      })
        .catch(e => {
          this.$message.error('获取失败')
          this.DuplicateCheck_loading = false
        })
    },
    handleInsertLink() {
      // this.handleClickSave('1')
      this.insertlinkloading = true
      InsertInnerLink({ post_id: this.post_id }).then(response => {
        this.last_content = response.html
        this.$refs.mt.setContent(response.html)
        this.$message.success('插入成功')
        this.insertlink_processed = true
        this.insertlinkloading = false
      })
        .catch(e => {
          this.$message.error('获取失败')
          this.insertlinkloading = false
        })
    },
    handleChangeOwnerPass() {
      PutPost(this.post_id, JSON.stringify({
        owner_pass: this.owner_pass,
        put_finished: 1
      }))
        .then(response => {
          this.$notify({
            title: '成功',
            message: '修改状态成功',
            type: 'success',
            duration: 1000
          })
        })
        .catch(e => { })
    },
    changeShow(v) {
      console.log(v)
      this.show_configs = !this.show_configs
    },
    is_out_writer() {
      return has_permission()
    },
    handleFetchProjects() {
      this.projectsLoading = true
      GetProjects()
        .then(response => {
          this.projectsLoading = false
          this.projects = response.data.data
        })
        .catch(e => {
          this.projectsLoading = false
        })
    },
    handleFetchCategories() {
      this.categoriesLoading = true
      GetCategories()
        .then(response => {
          this.categoriesLoading = false
          this.categories = response.data.data
        })
        .catch(e => {
          this.categoriesLoading = false
        })
    },
    handleFetchLanguages() {
      this.languagesLoading = true
      GetLanguages()
        .then(response => {
          this.languagesLoading = false
          this.languages = response.data.data
        })
        .catch(e => {
          this.languagesLoading = false
        })
    },
    handleFetchWebs() {
      this.websLoading = true
      GetWebs()
        .then(response => {
          this.websLoading = false
          this.webs = response.data.data
        })
        .catch(e => {
          this.websLoading = false
        })
    },
    querySearch(queryString, cb) {
      if (queryString) {
        cb(
          this.titleTemplates.map(m => {
            return { 'value': m.replace(/{}/g, queryString) }
          })
        )
      } else {
        cb([])
      }
    },
    handleClickPublish() {
      this.promoteVisiable = true
    },
    changeWriterFinished() {
      PutPost(this.post_id, JSON.stringify({
        put_finished: 1,
        writer_finished: this.writer_finished
      }))
        .then(response => {
          this.$notify({
            title: '成功',
            message: '修改状态成功',
            type: 'success',
            duration: 1000
          })
          this.getList(false)
        })
        .catch(e => { })
    },
    handleThirdPublic() {
      this.$prompt('请输入发布的链接', '添加发布链接', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        SendPostRecord({
          post_id: this.post_id,
          url: value
        }).then(response => {
          // this.handleFetchTree()
          this.notify('保存成功')
        })
          .catch(() => {
            // this.treeLoading = false
          })
      }).catch(() => {
      })
    },
    handleClickSave(loading) {
      // 确保从编辑器获取最新内容
      if (this.$refs.mt) {
        const editorContent = this.$refs.mt.getContent()
        if (editorContent) {
          this.content = editorContent
        }
      }

      console.log('保存时的内容长度:', this.content?.length || 0)
      console.log('保存时的标题:', this.title)

      // 验证内容
      if (!this.content && !this.title) {
        this.$message.warning('请先输入标题或内容')
        this.pageLoading = false
        return
      }

      let version_name = ''
      if (loading === '1') {
        this.pageLoading = true
      } else if (loading === '2') {
        this.pageLoading = true
        version_name = prompt('版本名称:')
        if (!version_name) {
          version_name = ''
        }
      }
      this.imagesurls = this.getImageUrls(this.content)
      const vars = {
        project_id: this.project_id,
        category_id: this.category_id,
        language_id: this.language_id,
        source_id: this.source_id,
        webs: this.selected_webs,
        title: this.title,
        content: this.content,
        version_name: version_name,
        word_count: this.$refs.mt.getCount()
      }

      const x = this.post_id ? PutPost(this.post_id, JSON.stringify(vars)) : AddPost(JSON.stringify(vars))
      x.then(response => {
        this.last_content = this.content
        this.pageLoading = false
        if (response.data) {
          this.post_id = response.data.id || response.data
          this.basic_seo_warnings = response.data.basic_seo_warnings || []
        }

        this.notify('保存成功')
        const promise = new Promise(function(resolve, reject) {
          resolve()
        })
        promise.then(this.setCookies())
        // 保存成功后，检查翻译版本是否需要更新
        this.$nextTick(() => {
          this.checkAndSyncTranslateVersion()
        })
      }).catch(e => {
        this.pageLoading = false
      })
      // this.$nextTick(() => {
      //   this.$refs.mt.insertContent('abc<img alt="Smiley face" height="42" width="42" src=""/>')
      // })
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    handleGoogle(link) {
      window.open(link)
    },
    scrollTop() {
      window.scrollTo(0, 0)
    },
    handleFetchTitleTemplates() {
      this.titleLoading = true
      GetTitleTemplate()
        .then(response => {
          this.titleTemplates = response.data
          this.titleLoading = false
        })
        .catch(e => {
          this.titleTemplates = []
          this.titleLoading = false
        })
    },
    checkAndSave() {
      if (this.content) {
        if (!this.title) this.title = (new Date()).toLocaleString()
        if (this.last_content !== this.content) this.handleClickSave()
      }
    },
    setCookies() {
      if (this.category_id) setToken(CategoryKey, this.category_id)
      if (this.language_id) setToken(LanguageKey, this.language_id)
    },
    handleViewHistory() {
      this.historyVisible = true
    },
    handleImportSuccess(content) {
      this.title = content.title
    },
    applyHistory(data) {
      this.title = data.title
      this.$nextTick(() => {
        this.$refs.mt.setContent(data.content)
      })
      this.last_content = data.content
    },

    // 处理编辑器的保存事件
    handleEditorSave(content) {
      // 更新content数据
      this.content = content
      // 调用实际的保存方法
      this.handleClickSave('1')
    },

    // 返回上一页
    goBack() {
      this.checkBeforeLeave(() => {
        this.$router.go(-1)
      })
    },

    // 跳转到首页
    goHome() {
      this.checkBeforeLeave(() => {
        this.$router.push('/')
      })
    },

    // 检查是否有未保存的内容
    hasUnsavedChanges() {
      // 从编辑器获取最新内容
      let currentContent = this.content
      if (this.$refs.mt) {
        const editorContent = this.$refs.mt.getContent()
        if (editorContent) {
          currentContent = editorContent
        }
      }

      // 检查内容是否有变化
      return currentContent !== this.last_content ||
             (this.title && this.title !== '' && !this.post_id)
    },

    // 离开前检查逻辑
    checkBeforeLeave(next) {
      if (this.hasUnsavedChanges()) {
        this.$confirm('您有未保存的更改，是否要保存后离开？', '提示', {
          confirmButtonText: '保存并离开',
          cancelButtonText: '直接离开',
          type: 'warning',
          showClose: false,
          closeOnClickModal: false,
          closeOnPressEscape: false
        }).then(() => {
          // 用户选择保存
          this.handleClickSave('1')
          // 等待保存完成后离开
          this.$nextTick(() => {
            if (typeof next === 'function') {
              next()
            }
          })
        }).catch(() => {
          // 用户选择直接离开
          if (typeof next === 'function') {
            next()
          }
        })
      } else {
        // 没有未保存的更改，直接离开
        if (typeof next === 'function') {
          next()
        }
      }
    },

    // 浏览器刷新/关闭前的提醒
    handleBeforeUnload(event) {
      if (this.hasUnsavedChanges()) {
        event.preventDefault()
        event.returnValue = '您有未保存的更改，确定要离开吗？'
        return '您有未保存的更改，确定要离开吗？'
      }
    },

    handleOpenTranslateTask() {
      // 检查是否有文章ID
      if (!this.post_id) {
        this.$message.warning('请先保存文章再进行翻译任务管理')
        return
      }
      // 打开翻译任务抽屉
      this.translateTaskVisible = true
    },

    // 刷新完整的 post 数据（包括翻译版本）
    refreshPostData() {
      if (!this.post_id) return

      GetPosts(this.post_id)
        .then(response => {
          // 更新翻译版本数据
          this.translateVersions = response.data.children || []

          // 更新其他相关数据
          this.basic_seo_warnings = response.data.basic_seo_warnings || []
          this.last_content = response.data.content

          // 如果有新的翻译版本，默认选择第一个
          if (this.translateVersions.length > 0 && !this.selectedTranslateVersion) {
            this.selectedTranslateVersion = this.translateVersions[0].id
            this.showTranslateCompare = true
          }

          console.log('Post数据已刷新，翻译版本数量:', this.translateVersions.length)
        })
        .catch(error => {
          console.error('刷新post数据失败:', error)
        })
    },

    // 处理翻译任务完成后的刷新
    handleTranslateTaskRefresh() {
      console.log('收到翻译任务刷新通知')
      this.refreshPostData()
    },

    // 获取选中的翻译版本内容
    getSelectedTranslateContent() {
      if (!this.selectedTranslateVersion || !this.translateVersions.length) {
        return null
      }
      return this.translateVersions.find(v => v.id === this.selectedTranslateVersion)
    },

    // 切换翻译版本
    handleTranslateVersionChange() {
      // 可以在这里添加版本切换的额外逻辑
      console.log('切换到翻译版本:', this.selectedTranslateVersion)

      // 重新初始化同步滚动
      this.$nextTick(() => {
        this.initSyncScroll()
      })
    },

    // 拖拽相关方法
    handleResizeStart(event) {
      this.isDragging = true
      this.startX = event.clientX
      this.startTranslateWidth = this.translateAreaWidth

      // 添加全局鼠标事件监听
      document.addEventListener('mousemove', this.handleResizeMove)
      document.addEventListener('mouseup', this.handleResizeEnd)

      // 防止文本选择
      document.body.style.userSelect = 'none'
      document.body.style.cursor = 'col-resize'

      event.preventDefault()
    },

    handleResizeMove(event) {
      if (!this.isDragging) return

      const containerWidth = this.$el.querySelector('.main-content').offsetWidth
      const deltaX = event.clientX - this.startX
      const deltaPercent = (deltaX / containerWidth) * 100

      let newTranslateWidth = this.startTranslateWidth + deltaPercent

      // 限制最小和最大宽度
      newTranslateWidth = Math.max(20, Math.min(70, newTranslateWidth))

      this.translateAreaWidth = newTranslateWidth
      this.editAreaWidth = 95 - newTranslateWidth // 考虑分割条宽度

      event.preventDefault()
    },

    handleResizeEnd() {
      this.isDragging = false

      // 移除全局鼠标事件监听
      document.removeEventListener('mousemove', this.handleResizeMove)
      document.removeEventListener('mouseup', this.handleResizeEnd)

      // 恢复样式
      document.body.style.userSelect = ''
      document.body.style.cursor = ''

      // 保存用户偏好到localStorage
      localStorage.setItem('translate-area-width', this.translateAreaWidth)
    },

    // 从localStorage恢复用户偏好
    restoreWidthPreference() {
      const savedWidth = localStorage.getItem('translate-area-width')
      if (savedWidth) {
        const width = parseFloat(savedWidth)
        // 如果保存的宽度不合理（比编辑器还大），使用默认值
        if (width >= 50) {
          this.resetWidthToDefault()
        } else {
          this.translateAreaWidth = width
          this.editAreaWidth = 95 - this.translateAreaWidth
        }
      }
    },

    // 主区域拖拽调整宽度相关方法（编辑区与侧边栏之间）
    handleMainResizeStart(event) {
      this.isMainDragging = true
      this.mainStartX = event.clientX
      this.mainStartSidebarWidth = this.sidebarWidth

      // 添加全局鼠标事件监听
      document.addEventListener('mousemove', this.handleMainResize)
      document.addEventListener('mouseup', this.handleMainResizeEnd)

      // 防止文本选择
      document.body.style.userSelect = 'none'
      document.body.style.cursor = 'col-resize'

      event.preventDefault()
    },

    handleMainResize(event) {
      if (!this.isMainDragging) return

      // 计算鼠标移动的距离（向右为正，向左为负）
      const deltaX = event.clientX - this.mainStartX

      // 计算新的侧边栏宽度（鼠标向右移动，侧边栏变窄；向左移动，侧边栏变宽）
      let newSidebarWidth = this.mainStartSidebarWidth - deltaX

      // 限制侧边栏最小和最大宽度
      const minSidebarWidth = 300 // 最小300px
      const maxSidebarWidth = 800 // 最大800px
      newSidebarWidth = Math.max(minSidebarWidth, Math.min(maxSidebarWidth, newSidebarWidth))

      this.sidebarWidth = newSidebarWidth

      event.preventDefault()
    },

    handleMainResizeEnd() {
      this.isMainDragging = false

      // 移除全局鼠标事件监听
      document.removeEventListener('mousemove', this.handleMainResize)
      document.removeEventListener('mouseup', this.handleMainResizeEnd)

      // 恢复样式
      document.body.style.userSelect = ''
      document.body.style.cursor = ''

      // 保存用户偏好到localStorage
      localStorage.setItem('sidebar-width', this.sidebarWidth)
    },

    // 从localStorage恢复侧边栏宽度偏好
    restoreSidebarWidth() {
      const savedWidth = localStorage.getItem('sidebar-width')
      if (savedWidth) {
        const width = parseInt(savedWidth)
        // 验证宽度合理性
        if (width >= 300 && width <= 800) {
          this.sidebarWidth = width
        }
      }
    },

    // 重置为默认宽度
    resetWidthToDefault() {
      this.translateAreaWidth = 42
      this.editAreaWidth = 53
      localStorage.setItem('translate-area-width', this.translateAreaWidth)
    },

    // ===== 同步滚动功能 =====

    // 初始化同步滚动
    initSyncScroll() {
      if (!this.showTranslateCompare || !this.translateVersions.length) return

      this.$nextTick(() => {
        this.setupScrollListeners()
        this.buildParagraphMaps()
      })
    },

    // 设置滚动监听器
    setupScrollListeners() {
      this.removeScrollListeners() // 先清除之前的监听器

      const editArea = this.getEditScrollArea()
      const translateArea = this.getTranslateScrollArea()

      console.log('设置滚动监听器:', {
        editArea: editArea,
        translateArea: translateArea,
        syncEnabled: this.syncScrollEnabled,
        mode: this.scrollSyncMode
      })

      if (!editArea || !translateArea) {
        console.warn('滚动容器未找到，无法设置同步滚动')
        return
      }

      // 编辑区域滚动监听
      this.editAreaScrollListener = this.debounce((e) => {
        console.log('编辑区域滚动事件触发:', e.target.scrollTop)
        if (!this.syncScrollEnabled || this.isScrollSyncing) {
          console.log('同步被跳过:', { enabled: this.syncScrollEnabled, syncing: this.isScrollSyncing })
          return
        }
        this.syncTranslateFromEdit(e.target)
      }, 50)

      // 翻译区域滚动监听
      this.translateAreaScrollListener = this.debounce((e) => {
        console.log('翻译区域滚动事件触发:', e.target.scrollTop)
        if (!this.syncScrollEnabled || this.isScrollSyncing) {
          console.log('同步被跳过:', { enabled: this.syncScrollEnabled, syncing: this.isScrollSyncing })
          return
        }
        this.syncEditFromTranslate(e.target)
      }, 50)

      // 绑定事件监听器
      editArea.addEventListener('scroll', this.editAreaScrollListener, { passive: true })
      translateArea.addEventListener('scroll', this.translateAreaScrollListener, { passive: true })

      console.log('滚动监听器绑定完成')

      // 测试滚动事件是否能正常触发
      setTimeout(() => {
        console.log('测试滚动事件...')
        if (editArea.scrollTop !== undefined) {
          console.log('编辑区域当前滚动位置:', editArea.scrollTop)
        }
        if (translateArea.scrollTop !== undefined) {
          console.log('翻译区域当前滚动位置:', translateArea.scrollTop)
        }
      }, 1000)
    },

    // 移除滚动监听器
    removeScrollListeners() {
      const editArea = this.getEditScrollArea()
      const translateArea = this.getTranslateScrollArea()

      if (editArea && this.editAreaScrollListener) {
        editArea.removeEventListener('scroll', this.editAreaScrollListener)
      }
      if (translateArea && this.translateAreaScrollListener) {
        translateArea.removeEventListener('scroll', this.translateAreaScrollListener)
      }
    },

    // 获取编辑区域的滚动容器
    getEditScrollArea() {
      // 应该检测 .editor-section 的滚动条，而不是更外层的容器
      let scrollContainer = document.querySelector('.edit-area .editor-section')

      // 如果没找到editor-section，再尝试其他选择器
      if (!scrollContainer) {
        scrollContainer = document.querySelector('.editor-section')
      }

      // 如果还是没找到，尝试AITiptap内部容器
      if (!scrollContainer) {
        const tiptapElement = this.$refs.mt?.$el
        if (tiptapElement) {
          scrollContainer = tiptapElement.querySelector('.tiptap-content') ||
                           tiptapElement.querySelector('.ProseMirror')
        }
      }

      console.log('找到的编辑滚动容器:', scrollContainer)

      // 检查元素是否真的可以滚动
      if (scrollContainer) {
        const style = window.getComputedStyle(scrollContainer)
        console.log('滚动容器样式:', {
          tagName: scrollContainer.tagName,
          className: scrollContainer.className,
          overflow: style.overflow,
          overflowY: style.overflowY,
          height: style.height,
          scrollHeight: scrollContainer.scrollHeight,
          clientHeight: scrollContainer.clientHeight,
          canScroll: scrollContainer.scrollHeight > scrollContainer.clientHeight
        })
      }

      return scrollContainer
    },

    // 获取翻译区域的滚动容器
    getTranslateScrollArea() {
      // 根据CSS样式，.translate-content-area 是滚动容器（有 overflow-y: auto）
      let translateContent = document.querySelector('.translate-content-area')

      // 如果没有找到，尝试查找翻译对照区域
      if (!translateContent) {
        translateContent = document.querySelector('.translate-compare-area')
      }

      console.log('找到的翻译滚动容器:', translateContent)

      // 检查元素是否真的可以滚动
      if (translateContent) {
        const style = window.getComputedStyle(translateContent)
        console.log('翻译容器样式:', {
          overflow: style.overflow,
          overflowY: style.overflowY,
          height: style.height,
          scrollHeight: translateContent.scrollHeight,
          clientHeight: translateContent.clientHeight,
          canScroll: translateContent.scrollHeight > translateContent.clientHeight
        })
      }

      return translateContent
    },

    // 从编辑区域同步到翻译区域
    syncTranslateFromEdit(editScrollArea) {
      const translateArea = this.getTranslateScrollArea()
      if (!translateArea) return

      this.isScrollSyncing = true

      if (this.scrollSyncMode === 'paragraph') {
        this.syncByParagraph(editScrollArea, translateArea, 'edit-to-translate')
      } else {
        this.syncByRatio(editScrollArea, translateArea)
      }

      // 延迟重置同步锁
      setTimeout(() => {
        this.isScrollSyncing = false
      }, 100)
    },

    // 从翻译区域同步到编辑区域
    syncEditFromTranslate(translateScrollArea) {
      const editArea = this.getEditScrollArea()
      if (!editArea) return

      this.isScrollSyncing = true

      if (this.scrollSyncMode === 'paragraph') {
        this.syncByParagraph(translateScrollArea, editArea, 'translate-to-edit')
      } else {
        this.syncByRatio(translateScrollArea, editArea)
      }

      // 延迟重置同步锁
      setTimeout(() => {
        this.isScrollSyncing = false
      }, 100)
    },

    // 基于比例的同步滚动（方案1）
    syncByRatio(sourceArea, targetArea) {
      const sourceScrollTop = sourceArea.scrollTop
      const sourceScrollHeight = sourceArea.scrollHeight - sourceArea.clientHeight

      if (sourceScrollHeight <= 0) return

      const scrollRatio = sourceScrollTop / sourceScrollHeight
      const targetScrollHeight = targetArea.scrollHeight - targetArea.clientHeight
      const targetScrollTop = scrollRatio * targetScrollHeight

      // 使用requestAnimationFrame平滑滚动
      requestAnimationFrame(() => {
        targetArea.scrollTop = Math.max(0, targetScrollTop)
      })
    },

    // 基于段落的智能同步（方案2）
    syncByParagraph(sourceArea, targetArea, direction) {
      const currentParagraph = this.getCurrentVisibleParagraph(sourceArea, direction.startsWith('edit') ? 'edit' : 'translate')
      if (currentParagraph === -1) return

      let targetParagraphIndex = currentParagraph
      const targetParagraphs = direction.startsWith('edit') ? this.translateParagraphMap : this.editParagraphMap

      // 确保目标段落索引不超出范围
      if (targetParagraphIndex >= targetParagraphs.length) {
        targetParagraphIndex = targetParagraphs.length - 1
      }

      if (targetParagraphIndex >= 0 && targetParagraphs[targetParagraphIndex]) {
        const targetParagraphTop = targetParagraphs[targetParagraphIndex].offsetTop

        requestAnimationFrame(() => {
          targetArea.scrollTop = Math.max(0, targetParagraphTop - 50) // 50px offset for better visibility
        })
      }
    },

    // 获取当前可见的段落索引
    getCurrentVisibleParagraph(scrollArea, areaType) {
      const paragraphs = areaType === 'edit' ? this.editParagraphMap : this.translateParagraphMap
      const scrollTop = scrollArea.scrollTop
      const visibleTop = scrollTop + scrollArea.clientHeight / 3 // 取可视区域上1/3处作为基准

      for (let i = 0; i < paragraphs.length; i++) {
        const paragraph = paragraphs[i]
        if (paragraph.offsetTop <= visibleTop && paragraph.offsetTop + paragraph.offsetHeight > visibleTop) {
          return i
        }
      }

      return -1
    },

    // 构建段落映射表
    buildParagraphMaps() {
      this.buildEditParagraphMap()
      this.buildTranslateParagraphMap()
    },

    // 构建编辑区域段落映射表
    buildEditParagraphMap() {
      const editArea = this.getEditScrollArea()
      if (!editArea) return

      const paragraphSelectors = 'p, h1, h2, h3, h4, h5, h6, div[data-paragraph], .paragraph'
      const paragraphs = editArea.querySelectorAll(paragraphSelectors)

      this.editParagraphMap = Array.from(paragraphs).map(p => ({
        element: p,
        offsetTop: p.offsetTop,
        offsetHeight: p.offsetHeight,
        text: p.textContent?.trim() || ''
      }))
    },

    // 构建翻译区域段落映射表
    buildTranslateParagraphMap() {
      const translateArea = this.getTranslateScrollArea()
      if (!translateArea) return

      const paragraphSelectors = 'p, h1, h2, h3, h4, h5, h6, div[data-paragraph], .paragraph'
      const paragraphs = translateArea.querySelectorAll(paragraphSelectors)

      this.translateParagraphMap = Array.from(paragraphs).map(p => ({
        element: p,
        offsetTop: p.offsetTop,
        offsetHeight: p.offsetHeight,
        text: p.textContent?.trim() || ''
      }))
    },

    // 切换同步滚动开关
    toggleSyncScroll() {
      this.syncScrollEnabled = !this.syncScrollEnabled
      if (this.syncScrollEnabled) {
        this.initSyncScroll()
        this.$message.success('同步滚动已启用')
      } else {
        this.removeScrollListeners()
        this.$message.info('同步滚动已禁用')
      }
    },

    // 切换同步模式
    toggleSyncMode() {
      this.scrollSyncMode = this.scrollSyncMode === 'ratio' ? 'paragraph' : 'ratio'
      this.$message.info(`切换到${this.scrollSyncMode === 'ratio' ? '比例' : '段落'}同步模式`)

      if (this.syncScrollEnabled) {
        this.initSyncScroll()
      }
    },

    // 手动重新对齐
    realignScrollPosition() {
      const editArea = this.getEditScrollArea()
      const translateArea = this.getTranslateScrollArea()

      if (!editArea || !translateArea) return

      // 重新构建段落映射
      this.buildParagraphMaps()

      // 基于当前编辑区域位置重新对齐
      this.syncTranslateFromEdit(editArea)

      this.$message.success('已重新对齐滚动位置')
    },

    // 获取翻译版本的最新内容
    async fetchTranslateVersionContent() {
      if (!this.selectedTranslateVersion) {
        console.log('没有选择的翻译版本')
        return false
      }

      try {
        console.log('获取翻译版本内容，ID:', this.selectedTranslateVersion)
        // 使用相同的GetPosts接口获取翻译版本内容
        const response = await GetPosts(this.selectedTranslateVersion)
        const newTranslateData = response.data

        // 找到当前翻译版本在数组中的位置
        const currentVersionIndex = this.translateVersions.findIndex(
          v => v.id === this.selectedTranslateVersion
        )
        if (currentVersionIndex === -1) {
          console.warn('未找到对应的翻译版本')
          return false
        }

        const currentVersion = this.translateVersions[currentVersionIndex]
        console.log('当前版本内容:', currentVersion.content?.substring(0, 100) + '...')
        console.log('新版本内容:', newTranslateData.content?.substring(0, 100) + '...')

        // 比较内容是否有变化
        const contentChanged = currentVersion.content !== newTranslateData.content ||
                              currentVersion.title !== newTranslateData.title

        if (contentChanged) {
          console.log('翻译版本内容已更新，正在刷新...')
          // 使用Vue.set确保响应式更新
          this.$set(this.translateVersions, currentVersionIndex, {
            ...currentVersion,
            title: newTranslateData.title,
            content: newTranslateData.content,
            updated_at: newTranslateData.updated_at
          })

          // 重新初始化同步滚动（因为内容结构可能发生变化）
          this.$nextTick(() => {
            this.initSyncScroll()
          })
          this.$message.success('翻译对照内容已更新')
          return true
        } else {
          console.log('翻译版本内容没有变化')
          // 即使内容没有变化，也显示一个提示
          this.$message.info('翻译对照内容已是最新版本')
          return false
        }
      } catch (error) {
        console.error('获取翻译版本内容失败:', error)
        this.$message.error('获取翻译对照内容失败')
        return false
      }
    },

    // 自动检查并同步翻译版本内容
    async checkAndSyncTranslateVersion() {
      if (!this.selectedTranslateVersion || !this.showTranslateCompare) {
        return
      }
      const updated = await this.fetchTranslateVersionContent()
      return updated
    },

    // 工具方法：防抖
    debounce(func, wait) {
      let timeout
      return function executedFunction(...args) {
        const later = () => {
          clearTimeout(timeout)
          func(...args)
        }
        clearTimeout(timeout)
        timeout = setTimeout(later, wait)
      }
    }
  }
}
</script>

<style scoped>
  /* 新布局样式 */
  .edit-post-layout {
    height: 100vh;
    display: flex;
    flex-direction: column;
    overflow: visible; /* 允许浮动工具栏显示在容器外 */
  }

  /* 顶部工具栏 - 固定 */
  .top-toolbar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1000;
    background: #fff;
    border-bottom: 1px solid #e4e7ed;
    padding: 10px 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  }

  .toolbar-left {
    flex: 0 0 auto;
    display: flex;
    align-items: center;
    gap: 15px;
  }

  .toolbar-center {
    flex: 1;
    text-align: center;
  }

  .toolbar-center .el-tag {
    margin: 0 5px;
  }

  .toolbar-right {
    flex: 0 0 auto;
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .toolbar-item {
    margin: 0 !important;
  }

  .config-toggle {
    cursor: pointer;
    font-weight: 500;
    color: #409eff;
  }

  .history-btn {
    cursor: pointer;
    color: #1976d2;
    padding: 5px 10px;
    border-radius: 4px;
    transition: background-color 0.3s;
  }

  .history-btn:hover {
    background-color: #f5f7fa;
  }

  /* 配置区域 - 可折叠 */
  .config-area {
    position: fixed;
    top: 60px;
    left: 0;
    right: 0;
    z-index: 999;
    background: #f8f9fa;
    border-bottom: 1px solid #e4e7ed;
    padding: 15px 20px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  }

  .config-content {
    max-width: 1200px;
    margin: 0 auto;
  }

  /* 主体内容区域 */
  .main-content {
    display: flex;
    height: 100vh;
    padding-top: 60px; /* 为顶部工具栏留空间 */
    overflow: visible; /* 允许浮动工具栏显示在容器外 */
  }

  .main-content.with-config {
    padding-top: 120px; /* 当有配置区域时增加顶部间距 */
  }

  /* 左侧编辑区域 - 可滚动 */
  .edit-area {
    flex: 1;
    min-width: 0;
    border-right: 1px solid #e4e7ed;
    padding: 20px;
    display: flex;
    flex-direction: column;
    background: #fff;
    height: 100%;
    overflow: visible; /* 允许浮动工具栏显示在容器外 */
    /* 移除edit-area的滚动设置，避免双重滚动条 */
  }

  .edit-area .title-section {
    flex-shrink: 0;
    margin-bottom: 20px;
  }

  .edit-area .editor-section {
    flex: 1;
    /* editor-section 作为真正的滚动容器 */
    overflow-y: auto;
    overflow-x: visible; /* 允许水平方向浮动元素显示 */
    min-height: 0;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    background: #fff;
    position: relative; /* 为浮动工具栏提供定位上下文 */
  }

  .edit-area .status-section {
    flex-shrink: 0;
    margin-top: 20px;
  }

  .title-input-wrapper {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .title-input-wrapper .el-input {
    flex: 1;
  }

  .title-input-wrapper .el-button {
    margin-left: 8px;
    padding: 2px 4px;
    min-width: 24px;
    height: 24px;
    font-size: 12px;
    border-radius: 3px;
    transition: all 0.2s ease;
  }

  .title-input-wrapper .el-button:hover {
    background-color: #f5f7fa;
    transform: translateY(-1px);
  }

  /* 右侧功能区域 - 固定 */
  .sidebar-area {
    /* 宽度由 :style 动态控制,默认500px */
    flex-shrink: 0;
    background: #f8f9fa;
    overflow-y: auto;
    padding: 20px 15px;
    transition: width 0.1s ease;
  }

  .sidebar-card {
    margin-bottom: 15px;
  }

  /* Tab卡片样式 */
  .sidebar-tabs-card {
    margin-bottom: 15px;

    ::v-deep .el-card__body {
      padding: 0;
    }

    ::v-deep .el-tabs--border-card {
      box-shadow: none;
      border: none;
    }

    ::v-deep .el-tabs__content {
      padding: 0;
    }

    .tab-content-wrapper {
      height: calc(100vh - 200px); /* 动态高度,根据视口高度调整 */
      min-height: 500px;
      max-height: 800px;
      overflow: hidden; /* 防止双重滚动条 */
      display: flex;
      flex-direction: column;

      /* 确保AI助手组件占满容器 */
      > div {
        flex: 1;
        display: flex;
        flex-direction: column;
      }
    }
  }

  /* 兼容原有样式 */
  .el-input--mini .el-input__inner {
    height: 28px;
    line-height: 28px;
    width: auto;
  }

  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .head {
    width: auto;
  }

  .app-container >>> .el-dialog {
    margin-top: 48px !important;
    margin-bottom: 68px;
  }

  .mt-detail:hover, .svg-icon:hover {
    cursor: pointer;
  }

  .mt-detail {
    color: #1976d2;
  }

  .mt-dialog >>> .el-dialog {
    margin: 88px auto !important;
  }

  .clearfix ::after {
    content: "";
    clear: both
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .toolbar-right {
      flex-wrap: wrap;
      gap: 5px;
    }

    /* 小屏幕下侧边栏默认宽度调整,仍可手动拖拽 */
    .sidebar-area {
      /* 宽度由 :style 动态控制 */
    }

    .main-content {
      flex-direction: column;
    }

    .edit-area {
      border-right: none;
      border-bottom: 1px solid #e4e7ed;
    }
  }

  /* 翻译版本对照区域样式 */
  .translate-compare-area {
    min-width: 300px;
    background: #f8f9fa;
    border-right: 1px solid #e4e7ed;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    transition: width 0.1s ease;
  }

  .translate-header {
    padding: 10px 15px;
    background: #fff;
    border-bottom: 1px solid #e4e7ed;
    flex-shrink: 0;
  }

  .translate-header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 15px;
  }

  .translate-select-section {
    display: flex;
    align-items: center;
    gap: 10px;
    flex-shrink: 0;
  }

  .translate-title {
    font-weight: 500;
    color: #606266;
    white-space: nowrap;
    font-size: 13px;
  }

  .translate-controls {
    display: flex;
    align-items: center;
    gap: 2px;
    flex-shrink: 0;
  }

  .translate-content-area {
    flex: 1;
    overflow-y: auto;
    padding: 15px;
  }

  .translate-title-display {
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e4e7ed;
    font-size: 16px;
    line-height: 1.5;
  }

  .translate-content-display {
    font-size: 14px;
    line-height: 1.6;
    color: #606266;
    word-wrap: break-word;
  }

  .translate-content-display >>> h1,
  .translate-content-display >>> h2,
  .translate-content-display >>> h3,
  .translate-content-display >>> h4,
  .translate-content-display >>> h5,
  .translate-content-display >>> h6 {
    margin: 15px 0 10px 0;
    color: #303133;
  }

  .translate-content-display >>> p {
    margin: 10px 0;
  }

  .translate-content-display >>> img {
    max-width: 100%;
    height: auto;
    border-radius: 4px;
    margin: 10px 0;
  }

  .translate-content-display >>> blockquote {
    margin: 15px 0;
    padding: 10px 15px;
    background: #f5f7fa;
    border-left: 4px solid #409eff;
    border-radius: 4px;
  }

  .translate-content-display >>> pre {
    background: #f5f7fa;
    padding: 10px;
    border-radius: 4px;
    overflow-x: auto;
    font-size: 13px;
  }

  .translate-content-display >>> code {
    background: #f5f7fa;
    padding: 2px 4px;
    border-radius: 3px;
    font-size: 13px;
  }

  /* 翻译对照区域表格样式 */
  .translate-content-display >>> table {
    width: 100%;
    border-collapse: collapse;
    margin: 15px 0;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    overflow: hidden;
  }

  .translate-content-display >>> table th {
    background-color: #f5f7fa;
    color: #303133;
    font-weight: 600;
    padding: 12px 8px;
    text-align: left;
    border-bottom: 2px solid #e4e7ed;
    border-right: 1px solid #e4e7ed;
  }

  .translate-content-display >>> table th:last-child {
    border-right: none;
  }

  .translate-content-display >>> table td {
    padding: 10px 8px;
    border-bottom: 1px solid #ebeef5;
    border-right: 1px solid #ebeef5;
    vertical-align: top;
  }

  .translate-content-display >>> table td:last-child {
    border-right: none;
  }

  .translate-content-display >>> table tr:last-child td {
    border-bottom: none;
  }

  .translate-content-display >>> table tr:nth-child(even) {
    background-color: #fafbfc;
  }

  .translate-content-display >>> table tr:hover {
    background-color: #f0f9ff;
  }

  /* 可拖拽分割条样式 */
  .resize-handle {
    width: 5px;
    background: #e4e7ed;
    cursor: col-resize;
    position: relative;
    flex-shrink: 0;
    transition: background-color 0.2s ease;
  }

  .resize-handle:hover {
    background-color: #409eff;
  }

  .resize-handle:hover .resize-line {
    opacity: 1;
  }

  .resize-line {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 1px;
    height: 30px;
    background: #909399;
    opacity: 0.5;
    transition: opacity 0.2s ease;
  }

  /* 主区域拖拽调整宽度 - 编辑区与侧边栏之间 */
  .main-resize-handle {
    width: 5px;
    background: #e4e7ed;
    cursor: col-resize;
    position: relative;
    flex-shrink: 0;
    transition: background-color 0.2s ease;
    z-index: 10;
  }

  .main-resize-handle:hover {
    background-color: #409eff;
  }

  .main-resize-handle:hover .resize-line {
    opacity: 1;
  }

  /* 编辑区域调整 */
  .edit-area.with-translate {
    min-width: 300px;
    transition: width 0.1s ease;
  }

  /* 当显示翻译对照时的响应式调整 */
  @media (max-width: 1200px) {
    .translate-compare-area {
      min-width: 250px;
    }

    .edit-area.with-translate {
      min-width: 250px;
    }

    .resize-handle {
      width: 8px;
    }
  }

  @media (max-width: 768px) {
    .translate-compare-area {
      display: none;
    }

    .resize-handle {
      display: none;
    }

    .edit-area.with-translate {
      width: 100% !important;
      min-width: 0;
    }
  }

  /* 翻译控制按钮样式 */
  .translate-controls .el-button {
    padding: 2px 4px;
    font-size: 12px;
    border-radius: 3px;
    transition: all 0.2s ease;
    min-width: 24px;
    height: 24px;
    margin: 0 1px;
  }

  .translate-controls .el-button.sync-enabled {
    color: #409eff;
    background-color: #ecf5ff;
  }

  .translate-controls .el-button:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  /* 响应式调整 */
  @media (max-width: 1200px) {
    .translate-header-content {
      flex-direction: column;
      align-items: flex-start;
      gap: 10px;
    }

    .translate-controls {
      justify-content: flex-end;
      width: 100%;
    }
  }

  /* 保持编辑器失焦时的选中高亮效果 */
  /* 使用 mark 实现持久的视觉高亮标记 */
  ::v-deep .ProseMirror mark[data-type="highlight"] {
    background-color: #b3d4fc;
    padding: 0;
    border-radius: 0;
  }

  ::v-deep .ProseMirror .highlight {
    background-color: #b3d4fc;
    padding: 0;
    border-radius: 0;
  }
</style>
